<?php
namespace Common\Models;
use Common\BaseModel;
class Wallets extends BaseModel
{
    public $res;
    public $redis_key = "wallets_";

    public function getSource()
    {
        return "f_wallets";
    }

    public function initialize()
    {
        parent::initialize();
    }


    /**
     * @func 根据用户id返回用户的余额信息
     * @param $uid 用户id
     * @return mixed 返回用户的余额信息
     */
    public function findbyUserId($uid)
    {
        return $this->findFirstByUserId($uid);
    }


    public function myWallets($user_id)
    {
        $res = $this::findFirstByUserId($user_id);
        if (empty($res)) {
            return false;
        } else {
            return $res->toarray();
        }
    }

    public function findbyUserMoney($user_id)
    {
        $condition['conditions'] = "user_id = $user_id";
        $condition['columns']    = "amount";
        $res                     = $this->findFirst($condition);
        if ($res == false) {
            return 0;
        }
        return doubleval($res->amount);
    }

    public function upgold($user_id, $pond)
    {
        if ($pond == 0) {
            return -1;
        }
        $res = $this->findFirstByUserId($user_id);
        if ($res) {
            if ($res->gold == null) {
                $res->gold = $pond;
            } else {
                $res->gold += $pond;
            }
            $res->save();
            return 1;
        } else {
            return -2;
        }
    }

    public function exchange_gold($params)
    {
        $res['res'] = false;
        $user_info  = $this->findFirstByUserId($params['user_id']);
        //元宝池
        $yuanbao_pone = 0;
        $luck         = 0;
        $gold         = doubleval($params['gold']);
        if ($gold < 1) {
            $res['msg'] = '最低1金币起兑';
            return $res;
        }
        if ($gold > doubleval($user_info->gold)) {
            $res['msg'] = '金币额度不足';
            return $res;
        }
//兑换现金
        if ($params['type'] == 'cash') {
            $user_info->ad_amount += $gold * 0.8;
            $yuanbao_pone         = $gold * 0.2;


            $user_info->gold -= $gold;
            $user_info->save();
            $ad_money_exchange_log               = new AdMoneyExchangeLog();
            $ad_money_exchange_log->user_id      = $params['user_id'];
            $ad_money_exchange_log->changge_type = 'gold_to_cash';
            $ad_money_exchange_log->old_coin     = $gold;
            $ad_money_exchange_log->new_coin     = $gold * 0.8;
            $ad_money_exchange_log->date         = date('Y-m-d H:i:s');
            $ad_money_exchange_log->save();
        }
        if ($params['type'] == 'yuanbao') {
            if ($gold != 1) {
                $res['msg'] = '抽奖金币只能为1';
                return $res;
            }

            $adturnable = new AdReturnTable();
            $luck       = $adturnable->probability(); //用户摇中的元宝数

            $ad_pond     = new AdPond();
            $is_exchange = $ad_pond->exchange_yuanbao(0, $luck);
            if ($is_exchange == false) {
                $res['msg'] = '元宝今日已兑换完';
                return $res;
            }
//	$num=rand(1,1001);
//	if($num <= 990){
//	$luck=1;
//	}
//	if($num <= 1000 && $num > 990){
//	$luck=10;
//	}
//	if($num == 1001){
//	$luck = 100;
//	}
            $yuanbao_pone       = 1;
            $user_info->gold    -= 1;
            $user_info->yuanbao += $luck;
            $user_info->save();
            $ad_money_exchange_log               = new AdMoneyExchangeLog();
            $ad_money_exchange_log->user_id      = $params['user_id'];
            $ad_money_exchange_log->changge_type = 'gold_to_yuanbao';
            $ad_money_exchange_log->old_coin     = $gold;
            $ad_money_exchange_log->new_coin     = $luck;
            $ad_money_exchange_log->date         = date('Y-m-d H:i:s');
            $ad_money_exchange_log->save();

        }
        $res['yuanbao_pone'] = $yuanbao_pone;
        $res['luck']         = $luck;
        $res['res']          = true;
        return $res;

    }

    public function sum_yuambao()
    {
        $condition['columns'] = 'sum(yuanbao) as yuanbao';
        $res                  = $this->findFirst($condition);
        return round(doubleval($res->yuanbao), 2);
    }

    public function exchange_yuanbao($price)
    {
        $condition['conditions'] = "yuanbao >0";
        //$condition['limit']=100;
        $res = $this->find($condition);
        if ($res->toarray() != []) {
            foreach ($res as $k => $v) {
                $ad_money_exchange_log               = new AdMoneyExchangeLog();
                $ad_money_exchange_log->user_id      = $v->user_id;
                $ad_money_exchange_log->changge_type = 'yuanbao_to_cash';
                $ad_money_exchange_log->old_coin     = $v->yuanbao;
                $ad_money_exchange_log->new_coin     = $v->yuanbao * $price;
                $ad_money_exchange_log->date         = date('Y-m-d H:i:s');
                $ad_money_exchange_log->save();
                $v->ad_amount += $v->yuanbao * $price;
                $v->yuanbao   = $v->yuanbao * (1 - $price);
                $v->save();
                //日志
            }
            return true;
        }
        return true;
    }

    public function save_params($params)
    {
        return $this::save($params);
    }

    public function save_sms($user_id, $money)
    {
        $res = $this->findFirstByUserId($user_id);
        if ($res) {
            $res->gold = $money;

            $res->save();
            return true;
        }
        return false;
    }

    /**
     * @param $ServiceCharge 手续费
     * @param int $ratio 回收元宝比例
     * @param int $jb_ratio 金币元宝比例
     * @return array
     */
//    public function compulsory_recovery($ServiceCharge, $ratio = 0, $jb_ratio = 20000, $is_manual = 0)
    public function compulsory_recovery($yuanbao,$is_manual = 0)
    {
        $condition['conditions'] = "yuanbao > 0";
        $res                     = $this->find($condition);
        $sm_num                  = 0;
        $dates                   = date('Y-m-d H:i:s');
        $batchList               = array();
        foreach ($res as $k => $v) {
            $temp['user_id']      = $v->user_id;
            $temp['changge_type'] = 'yuanbao_to_cach';
            $temp['old_coin']     = $v->amount;
            //强制回收 系统会以1元/元宝强制回收50%，收取1%-10%手续费，用于给新会员购买//，老会员也可以持续买入，买入必须用金币
            if ($is_manual > 0) {

                //有回收比例 按照比例回收
                $sm_yb = round($v->yuanbao * ($yuanbao->ratio / 10000 - 1), 2);
                if ($yuanbao->forced_recovery_ratio > 0) {
                    $sm_yb += round($v->yuanbao * ($yuanbao->forced_recovery_ratio / 100),2);
                }
                if ($sm_yb <= 0) {
                    continue;
                }
                $new_coin = round($sm_yb * (1 - $yuanbao->service_charge / 100),2);
                $yb['is_manual'] = 1;
            } else {
                $yb['is_manual'] = 0;
                $sm_yb    = round($v->yuanbao,2);
                $new_coin = $v->yuanbao * (1 - $yuanbao->service_charge / 100);
            }
            $temp['new_coin'] = $v->amount + $new_coin;
            $temp['date']     = $dates;
            $batchList[]      = $temp;
            $sm_num           += $sm_yb;
        }

        $yb['yuanbao_num'] = $sm_num;
        $yb['ratio'] = $yuanbao->ratio;
        $yb['service_charge'] = $yuanbao->service_charge;
        $yb['oid_yuanbao_count'] = $yuanbao->fx_yb_num;
        $yb['oid_sm_yuanbao'] = $yuanbao->sm_yb_num;
        $yb['oid_yh_yuanbao'] = $yuanbao->yh_yb_num;
        $yb['this_yuanbao_count'] = $yuanbao->fx_yb_num+$sm_num;
        $yb['this_sm_yuanbao'] = $yuanbao->sm_yb_num+$sm_num;
        $yb['this_yh_yuanbao'] = $yuanbao->yh_yb_num;
        $yb['created_at'] = $dates;
        $logs = new YuanbaoRecoveryLog();
        $logs->save($yb);
        //写入日志
        $log = new AdMoneyExchangeLog();
        $log->batch_insert($batchList);

        return $sm_num;
    }

    //批量更新金币
    public function batch_update($updateStr, $updateId)
    {
        $updateSql = <<<ENT
UPDATE Wallets
    SET gold = CASE user_id
        $updateStr
    END
WHERE user_id IN ($updateId)
ENT;
        return $this->modelsManager->executeQuery($updateSql);
    }
}
